﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Reflection;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace HardwareMonitor
{
	static class Program
	{
		[DllImport("User32.dll")]
		private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
		[DllImport("User32.dll")]
		private static extern bool SetForegroundWindow(IntPtr hWnd);
		[DllImport("User32.dll")]
		private static extern IntPtr FindWindow(string pClassName, string pWindowName);

		private const int SW_SHOWNOMAL = 1;

		[STAThread]
		static void Main()
		{
			IntPtr handler = FindWindow(null, $"{Application.ProductName} - v{frmMain.version}");

			if (handler != IntPtr.Zero) {
				ShowWindowAsync(handler, SW_SHOWNOMAL);
				SetForegroundWindow(handler);

				return;
			}

#if !DEBUG
			AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
#endif

			Application.EnableVisualStyles();
			Application.SetCompatibleTextRenderingDefault(false);
			Application.Run(new frmMain());
		}

		private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
		{
			string resourceName = "HardwareMonitor.libs." + new AssemblyName(args.Name).Name + ".dll";
			using (var stream = Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceName)) {
				byte[] assemblyData = new byte[stream.Length];
				stream.Read(assemblyData, 0, assemblyData.Length);
				return Assembly.Load(assemblyData);
			}
		}
	}
}
